const { Op } = require('sequelize');

const seq = require('../db/seq');
const Indent = require('../model/indent');
const Goods = require('../model/goods');

const indent = Indent(seq);
const goods = Goods(seq);

class IndentController {
    //查询所有订单
    async getAll(ctx, next) {
        const user_id = ctx.state.user.user_id;
        try {
            const { count, rows } = await indent.findAndCountAll({
                include: {
                    model: goods,
                    as: 'goods_info',
                    attributes: ['goods_img'],
                },
                where: {
                    user_id: user_id
                }
            })
            ctx.body = {
                code: 0,
                message: '查询所有订单成功',
                result: {
                    count: count,
                    rows: rows
                }
            }
        } catch (err) {
            console.log('查询所有订单数据失败', err);
            return ctx.body = {
                error: '查询所有订单数据失败'
            }
        }
    }

    //查询特定状态订单
    async getIndent(ctx, next) {
        const user_id = ctx.state.user.user_id;
        const { indentStatus } = ctx.request.params;
        try {
            const { count, rows } = await indent.findAndCountAll({
                include: {
                    model: goods,
                    as: 'goods_info',
                    attributes: ['goods_img'],
                },
                where: {
                    [Op.and]: {
                        user_id,
                        indent_status: indentStatus
                    }
                }
            })
            ctx.body = {
                code: 0,
                message: '查询订单成功',
                result: {
                    count: count,
                    rows: rows
                }
            }
        } catch (err) {
            console.log('查询订单失败', err);
            return ctx.body = {
                error: '查询订单失败'
            }
        }
    }

    //删除订单
    async deleteIndent(ctx, next) {
        const { ids } = ctx.request.body;
        try {
            const res = indent.destroy({
                where: {
                    indent_id: {
                        [Op.in]: ids,
                    }
                }
            })
            ctx.body = {
                code: 0,
                message: '删除订单成功',
                result: res
            }
        } catch (err) {
            console.log('删除订单失败', err);
            return ctx.body = {
                error: '删除订单失败'
            }
        }
    }
}

module.exports = new IndentController();